package com.zm.xiaohashu.count.biz.consumer.db;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.util.concurrent.RateLimiter;
import com.zm.xiaohashu.count.biz.constant.MQConstants;
import com.zm.xiaohashu.count.biz.enums.FollowUnfollowTypeEnum;
import com.zm.xiaohashu.count.biz.mapper.UserCountMapper;
import com.zm.xiaohashu.count.biz.model.dto.CountFollowUnfollowMqDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;

@Component
@RocketMQMessageListener(consumerGroup = "xiaohashu_group_" + MQConstants.TOPIC_COUNT_FOLLOWING_2_DB, // Group 组
        topic = MQConstants.TOPIC_COUNT_FOLLOWING_2_DB // 主题 Topic
)
@Slf4j
public class CountFollowing2DBConsumer implements RocketMQListener<String> {
    // 每秒创建 5000 个令牌
    private RateLimiter rateLimiter = RateLimiter.create(5000);
    @Resource
    private UserCountMapper userCountMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(String body) {
        if (StrUtil.isBlank(body)) return;
        log.info("## 消费到了 MQ 【计数: 粉丝数入库】, {}...", body);
        rateLimiter.acquire();
        CountFollowUnfollowMqDTO countFollowUnfollowMqDTO = JSONUtil.toBean(body, CountFollowUnfollowMqDTO.class);
        Long userId = countFollowUnfollowMqDTO.getUserId();
        Integer type = countFollowUnfollowMqDTO.getType();
        Integer total = Objects.equals(type, FollowUnfollowTypeEnum.FOLLOW.getCode()) ? 1 : -1;
        userCountMapper.insertOrUpdateFollowingTotal(userId, total);
    }

}